<template>
  <div class="order-detail-page min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="lg:max-w-[1200px] mx-auto">
        <!-- 返回按钮 -->
        <div class="mb-6">
          <el-button
            link
            class="!px-0 !h-auto text-gray-600 hover:text-primary-600 dark:text-gray-400 dark:hover:text-primary-400"
            @click="handleBack"
          >
            <el-icon class="mr-2"><ArrowLeft /></el-icon>
            返回订单列表
          </el-button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="py-8">
          <el-skeleton :rows="10" animated />
        </div>

        <template v-else>
          <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
            <!-- 左侧主要内容 -->
            <div class="lg:col-span-8 space-y-6">
              <!-- 订单状态卡片 -->
              <div
                class="bg-white dark:bg-gray-800 rounded-lg shadow-sm dark:border dark:border-gray-700 overflow-hidden"
              >
                <div
                  class="bg-primary-500 dark:bg-primary-600 text-white px-6 py-6"
                >
                  <div class="flex items-center justify-between">
                    <div>
                      <h2 class="text-xl font-medium mb-2">
                        {{ getStatusText }}
                      </h2>
                      <p class="text-primary-100 text-sm">
                        {{ getStatusDescription }}
                      </p>
                    </div>
                    <div class="text-right">
                      <div class="text-sm mb-2">订单金额</div>
                      <div class="text-2xl font-bold">
                        ¥{{ orderInfo.payableAmount.toFixed(2) }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 商品信息卡片 -->
              <div
                class="bg-white dark:bg-gray-800 rounded-lg shadow-sm dark:border dark:border-gray-700 overflow-hidden"
              >
                <div
                  class="px-6 py-4 border-b border-gray-100 dark:border-gray-700"
                >
                  <h3 class="text-lg font-medium dark:text-gray-100">
                    {{ orderInfo.type === "hotel" ? "预订信息" : "商品信息" }}
                  </h3>
                </div>
                <div class="p-6">
                  <!-- 酒店预订信息 -->
                  <template v-if="orderInfo.type === 'hotel'">
                    <div class="space-y-6">
                      <!-- 酒店信息 -->
                      <div
                        class="flex items-start gap-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
                      >
                        <el-image
                          :src="orderInfo.booking?.roomImage"
                          class="w-32 h-32 rounded-lg object-cover"
                        />
                        <div class="flex-1">
                          <h4
                            class="text-lg font-medium mb-2 dark:text-gray-100"
                          >
                            {{ orderInfo.booking?.hotelName }}
                          </h4>
                          <p class="text-gray-600 dark:text-gray-400 mb-2">
                            {{ orderInfo.booking?.roomName }}
                          </p>
                          <div
                            class="flex items-center text-sm text-gray-500 dark:text-gray-400"
                          >
                            <span>{{
                              formatDate(
                                orderInfo.booking?.checkIn,
                                "YYYY-MM-DD",
                              )
                            }}</span>
                            <el-icon class="mx-2"><ArrowRight /></el-icon>
                            <span>{{
                              formatDate(
                                orderInfo.booking?.checkOut,
                                "YYYY-MM-DD",
                              )
                            }}</span>
                            <span class="ml-2"
                              >({{ orderInfo.booking?.nights }}晚)</span
                            >
                          </div>
                        </div>
                        <div class="text-right">
                          <div
                            class="text-lg font-medium text-primary-600 dark:text-primary-400"
                          >
                            ¥{{ orderInfo.booking?.price
                            }}<span class="text-sm">/晚</span>
                          </div>
                          <div class="text-sm text-gray-500 dark:text-gray-400">
                            {{ orderInfo.booking?.roomCount }}间
                          </div>
                        </div>
                      </div>

                      <!-- 入住人信息 -->
                      <div class="space-y-4">
                        <h4 class="font-medium dark:text-gray-100">
                          入住人信息
                        </h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div
                            v-for="(guest, index) in orderInfo.booking?.guests"
                            :key="index"
                            class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
                          >
                            <div class="flex items-center mb-2">
                              <span
                                class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-2 text-sm"
                              >
                                {{ index + 1 }}
                              </span>
                              <span class="font-medium dark:text-gray-100"
                                >入住人信息</span
                              >
                            </div>
                            <div class="space-y-2 text-sm">
                              <div class="flex justify-between">
                                <span class="text-gray-500 dark:text-gray-400"
                                  >姓名</span
                                >
                                <span
                                  class="text-gray-900 dark:text-gray-100"
                                  >{{ guest.name }}</span
                                >
                              </div>
                              <div class="flex justify-between">
                                <span class="text-gray-500 dark:text-gray-400"
                                  >证件类型</span
                                >
                                <span class="text-gray-900 dark:text-gray-100">
                                  {{
                                    guest.idType === "idcard"
                                      ? "身份证"
                                      : "护照"
                                  }}
                                </span>
                              </div>
                              <div class="flex justify-between">
                                <span class="text-gray-500 dark:text-gray-400"
                                  >证件号码</span
                                >
                                <span
                                  class="text-gray-900 dark:text-gray-100"
                                  >{{ guest.idNumber }}</span
                                >
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 联系人信息 -->
                      <div class="space-y-4">
                        <h4 class="font-medium dark:text-gray-100">
                          联系人信息
                        </h4>
                        <div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                          <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                              <span class="text-gray-500 dark:text-gray-400"
                                >联系人</span
                              >
                              <span class="text-gray-900 dark:text-gray-100">{{
                                orderInfo.booking?.contactName
                              }}</span>
                            </div>
                            <div class="flex justify-between">
                              <span class="text-gray-500 dark:text-gray-400"
                                >联系电话</span
                              >
                              <span class="text-gray-900 dark:text-gray-100">{{
                                orderInfo.booking?.contactPhone
                              }}</span>
                            </div>
                            <div class="flex justify-between">
                              <span class="text-gray-500 dark:text-gray-400"
                                >电子邮箱</span
                              >
                              <span class="text-gray-900 dark:text-gray-100">{{
                                orderInfo.booking?.contactEmail
                              }}</span>
                            </div>
                            <div class="flex justify-between">
                              <span class="text-gray-500 dark:text-gray-400"
                                >预计到店</span
                              >
                              <span class="text-gray-900 dark:text-gray-100">{{
                                orderInfo.booking?.arrivalTime
                              }}</span>
                            </div>
                            <div class="flex justify-between">
                              <span class="text-gray-500 dark:text-gray-400"
                                >特殊要求</span
                              >
                              <span class="text-gray-900 dark:text-gray-100">{{
                                orderInfo.booking?.specialRequests || "无"
                              }}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>

                  <!-- 商品订单信息 -->
                  <template v-else>
                    <div class="space-y-4">
                      <div
                        v-for="(item, index) in orderInfo.items"
                        :key="index"
                        class="flex gap-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
                      >
                        <el-image
                          :src="item.image"
                          class="w-24 h-24 object-cover rounded-lg"
                        />
                        <div class="flex-1">
                          <div class="flex justify-between">
                            <div>
                              <h4
                                class="text-base font-medium mb-2 dark:text-gray-100"
                              >
                                {{ item.title }}
                              </h4>
                              <p
                                class="text-sm text-gray-500 dark:text-gray-400"
                              >
                                {{ item.specs }}
                              </p>
                            </div>
                            <div class="text-right">
                              <div
                                class="text-lg font-medium text-primary-600 dark:text-primary-400"
                              >
                                ¥{{ item.price }}
                              </div>
                              <div
                                class="text-sm text-gray-500 dark:text-gray-400"
                              >
                                x{{ item.quantity }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>

              <!-- 物流信息卡片 - 仅商品订单显示 -->
              <div
                v-if="orderInfo.type === 'product'"
                class="bg-white dark:bg-gray-800 rounded-lg shadow-sm dark:border dark:border-gray-700 overflow-hidden"
              >
                <div
                  class="px-6 py-4 border-b border-gray-100 dark:border-gray-700"
                >
                  <h3 class="text-lg font-medium dark:text-gray-100">
                    物流信息
                  </h3>
                </div>
                <div class="p-6">
                  <!-- 物流进度 -->
                  <el-steps
                    :active="getLogisticsStep()"
                    finish-status="success"
                    class="mb-6"
                  >
                    <el-step
                      title="提交订单"
                      :description="formatDate(orderInfo.createTime)"
                    />
                    <el-step
                      title="付款成功"
                      :description="formatDate(orderInfo.payTime)"
                    />
                    <el-step
                      title="商品出库"
                      :description="formatDate(orderInfo.shipTime)"
                    />
                    <el-step
                      title="交易完成"
                      :description="formatDate(orderInfo.finishTime)"
                    />
                  </el-steps>

                  <!-- 物流详情 -->
                  <div
                    v-if="orderInfo.logistics"
                    class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4"
                  >
                    <div class="flex items-center justify-between mb-4">
                      <div>
                        <span class="text-gray-500 dark:text-gray-400"
                          >物流公司：</span
                        >
                        <span class="text-gray-900 dark:text-gray-100">{{
                          orderInfo.logistics.company
                        }}</span>
                      </div>
                      <div>
                        <span class="text-gray-500 dark:text-gray-400"
                          >运单号：</span
                        >
                        <span
                          class="text-gray-900 dark:text-gray-100 font-mono"
                          >{{ orderInfo.logistics.trackingNo }}</span
                        >
                        <el-button
                          type="primary"
                          link
                          class="ml-2"
                          @click="copyTrackingNo"
                          >复制</el-button
                        >
                      </div>
                    </div>
                    <el-timeline>
                      <el-timeline-item
                        v-for="(activity, index) in orderInfo.logistics
                          .activities"
                        :key="index"
                        :timestamp="activity.time"
                        :type="index === 0 ? 'primary' : ''"
                      >
                        {{ activity.content }}
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                </div>
              </div>
            </div>

            <!-- 右侧侧边栏 -->
            <div class="lg:col-span-4">
              <div class="lg:sticky lg:top-24 space-y-6">
                <!-- 订单信息卡片 -->
                <div
                  class="bg-white dark:bg-gray-800 rounded-lg shadow-sm dark:border dark:border-gray-700 overflow-hidden"
                >
                  <div
                    class="px-6 py-4 border-b border-gray-100 dark:border-gray-700"
                  >
                    <h3 class="text-lg font-medium dark:text-gray-100">
                      订单信息
                    </h3>
                  </div>
                  <div class="p-6">
                    <div class="space-y-4">
                      <div class="flex justify-between">
                        <span class="text-gray-500 dark:text-gray-400"
                          >订单编号</span
                        >
                        <span
                          class="text-gray-900 dark:text-gray-100 font-mono"
                          >{{ orderInfo.orderNo }}</span
                        >
                      </div>
                      <div class="flex justify-between">
                        <span class="text-gray-500 dark:text-gray-400"
                          >下单时间</span
                        >
                        <span class="text-gray-900 dark:text-gray-100">{{
                          formatDate(orderInfo.createTime)
                        }}</span>
                      </div>
                      <div class="flex justify-between">
                        <span class="text-gray-500 dark:text-gray-400"
                          >支付方式</span
                        >
                        <span class="text-gray-900 dark:text-gray-100">{{
                          orderInfo.paymentMethod === "wechat"
                            ? "微信支付"
                            : "支付宝"
                        }}</span>
                      </div>
                      <div class="flex justify-between">
                        <span class="text-gray-500 dark:text-gray-400"
                          >支付时间</span
                        >
                        <span class="text-gray-900 dark:text-gray-100">{{
                          formatDate(orderInfo.payTime)
                        }}</span>
                      </div>
                      <div class="flex justify-between">
                        <span class="text-gray-500 dark:text-gray-400"
                          >订单状态</span
                        >
                        <el-tag :type="getStatusType">{{
                          getStatusText
                        }}</el-tag>
                      </div>
                      <div class="flex justify-between">
                        <span class="text-gray-500 dark:text-gray-400"
                          >订单备注</span
                        >
                        <span class="text-gray-900 dark:text-gray-100">{{
                          orderInfo.remark || "无"
                        }}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 费用信息卡片 -->
                <div
                  class="bg-white dark:bg-gray-800 rounded-lg shadow-sm dark:border dark:border-gray-700 overflow-hidden"
                >
                  <div
                    class="px-6 py-4 border-b border-gray-100 dark:border-gray-700"
                  >
                    <h3 class="text-lg font-medium dark:text-gray-100">
                      费用信息
                    </h3>
                  </div>
                  <div class="p-6">
                    <div class="space-y-4">
                      <!-- 酒店订单费用明细 -->
                      <template v-if="orderInfo.type === 'hotel'">
                        <div
                          class="flex justify-between text-gray-500 dark:text-gray-400"
                        >
                          <div>
                            <span>房费</span>
                            <span class="text-sm ml-2">
                              ({{ orderInfo.booking?.roomCount }}间 ×
                              {{ orderInfo.booking?.nights }}晚 × ¥{{
                                orderInfo.booking?.price
                              }})
                            </span>
                          </div>
                          <span>¥{{ orderInfo.booking?.totalAmount }}</span>
                        </div>
                        <div
                          class="flex justify-between text-gray-500 dark:text-gray-400"
                        >
                          <span>服务费</span>
                          <span>¥{{ orderInfo.booking?.serviceFee }}</span>
                        </div>
                      </template>

                      <!-- 商品订单费用明细 -->
                      <template v-else>
                        <div
                          class="flex justify-between text-gray-500 dark:text-gray-400"
                        >
                          <span>商品总额</span>
                          <span>¥{{ calculateProductTotal() }}</span>
                        </div>
                        <div
                          class="flex justify-between text-gray-500 dark:text-gray-400"
                        >
                          <span>运费</span>
                          <span>¥{{ orderInfo.shippingFee || 0 }}</span>
                        </div>
                      </template>

                      <div
                        class="border-t border-gray-100 dark:border-gray-700 pt-4 flex justify-between text-lg font-medium"
                      >
                        <span class="dark:text-gray-100">实付金额</span>
                        <span class="text-primary-600 dark:text-primary-400">
                          ¥{{ orderInfo.payableAmount.toFixed(2) }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 收货地址卡片 - 仅商品订单显示 -->
                <div
                  v-if="orderInfo.type === 'product'"
                  class="bg-white dark:bg-gray-800 rounded-lg shadow-sm dark:border dark:border-gray-700 overflow-hidden"
                >
                  <div
                    class="px-6 py-4 border-b border-gray-100 dark:border-gray-700"
                  >
                    <h3 class="text-lg font-medium dark:text-gray-100">
                      收货信息
                    </h3>
                  </div>
                  <div class="p-6">
                    <div class="space-y-2">
                      <div class="font-medium dark:text-gray-100">
                        {{ orderInfo.address?.name }}
                      </div>
                      <div class="text-gray-500 dark:text-gray-400">
                        {{ orderInfo.address?.phone }}
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">
                        {{ orderInfo.address?.fullAddress }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import axios from "@/api/axios";

const router = useRouter();
const route = useRoute();
const loading = ref(true);

// 订单信息
const orderInfo = ref({
  orderNo: "",
  type: "product",
  title: "",
  createTime: "",
  payTime: "",
  shipTime: "",
  finishTime: "",
  paymentMethod: "",
  payableAmount: 0,
  status: "paid",
  remark: "",
  items: [],
  booking: null,
  shippingFee: 0,
  logistics: null,
  address: null,
});

// 计算属性
const getStatusText = computed(() => {
  const statusMap = {
    unpaid: "待支付",
    paid: orderInfo.value.type === "hotel" ? "待入住" : "已支付",
    processing: "入住中",
    completed: orderInfo.value.type === "hotel" ? "已离店" : "已完成",
    cancelled: "已取消",
  };
  return statusMap[orderInfo.value.status] || "未知状态";
});

const getStatusDescription = computed(() => {
  const descMap = {
    unpaid: "请尽快完成支付，超时订单将自动取消",
    paid:
      orderInfo.value.type === "hotel"
        ? `请于${formatDate(orderInfo.value.booking?.checkIn, "YYYY-MM-DD")} 14:00后办理入住`
        : "支付成功，感谢您的购买",
    processing: "祝您入住愉快",
    completed:
      orderInfo.value.type === "hotel"
        ? "感谢您的入住，欢迎再次光临"
        : "订单已完成，欢迎再次购买",
    cancelled: "订单已取消",
  };
  return descMap[orderInfo.value.status] || "";
});

const getStatusType = computed(() => {
  const typeMap = {
    unpaid: "warning",
    paid: "success",
    processing: "primary",
    completed: "success",
    cancelled: "info",
  };
  return typeMap[orderInfo.value.status] || "info";
});

// 方法
const handleBack = () => {
  router.push("/user/orders");
};

const formatDate = (date, format = "YYYY-MM-DD HH:mm:ss") => {
  return date ? dayjs(date).format(format) : "";
};

const calculateProductTotal = () => {
  return orderInfo.value.items.reduce((total, item) => {
    return total + item.price * item.quantity;
  }, 0);
};

// 获取物流进度
const getLogisticsStep = () => {
  const { status } = orderInfo.value;
  const stepMap = {
    unpaid: 0,
    paid: 1,
    shipped: 2,
    completed: 3,
  };
  return stepMap[status] || 0;
};

// 复制运单号
const copyTrackingNo = async () => {
  try {
    await navigator.clipboard.writeText(orderInfo.value.logistics?.trackingNo);
    ElMessage.success("复制成功");
  } catch (error) {
    console.error("复制失败:", error);
    ElMessage.error("复制失败");
  }
};

// 获取订单详情
const fetchOrderDetail = async (orderId) => {
  try {
    loading.value = true;
    
    // 调用获取订单详情API
    try {
      const response = await axios.get(`/orders/${orderId}`);
      
      if (response) {
        // 使用API返回的数据
        orderInfo.value = response;
        return;
      }
    } catch (error) {
      console.error("获取订单详情API失败:", error);
      // 发生错误，使用测试数据
    }

    // 使用测试数据
    orderInfo.value = {
      orderNo: orderId,
      type: route.query.type || "product",
      title:
        route.query.type === "hotel"
          ? "贵港大酒店 - 豪华大床房"
          : "贵港特色手工艺品等2件商品",
      createTime: "2024-01-25 10:30:00",
      payTime: "2024-01-25 10:35:00",
      shipTime: "2024-01-25 14:30:00",
      finishTime: "2024-01-26 15:20:00",
      paymentMethod: "wechat",
      payableAmount: route.query.type === "hotel" ? 1073.6 : 188.0,
      status: route.query.type === "hotel" ? "paid" : "completed",
      remark: route.query.type === "hotel" ? "希望安排高层房间" : "",
      address:
        route.query.type === "hotel"
          ? null
          : {
              name: "张三",
              phone: "13800138000",
              fullAddress: "广西壮族自治区贵港市港北区贵港大道123号",
            },
      items:
        route.query.type === "hotel"
          ? []
          : [
              {
                id: 1,
                title: "贵港特色手工艺品",
                specs: "规格：标准款",
                price: 99,
                quantity: 1,
                image: "/images/products/product1.jpg",
              },
            ],
      logistics:
        route.query.type === "hotel"
          ? null
          : {
              company: "顺丰速运",
              trackingNo: "SF1234567890",
              activities: [
                {
                  time: "2024-01-26 15:20:00",
                  content: "已签收，签收人：张三，感谢使用顺丰快递",
                },
                {
                  time: "2024-01-26 09:30:00",
                  content: "【贵港市】快件已到达【贵港港北营业点】",
                },
                {
                  time: "2024-01-25 14:30:00",
                  content: "【贵港市】快件已从【贵港转运中心】发出",
                },
              ],
            },
      booking:
        route.query.type === "hotel"
          ? {
              hotelName: "贵港大酒店",
              roomName: "豪华大床房",
              roomImage: "/images/hotels/room1.jpg",
              checkIn: "2024-02-01",
              checkOut: "2024-02-03",
              nights: 2,
              roomCount: 1,
              price: 488,
              totalAmount: 976,
              serviceFee: 97.6,
              guests: [
                {
                  name: "张三",
                  idType: "idcard",
                  idNumber: "450800199001011234",
                },
              ],
              contactName: "张三",
              contactPhone: "13800138000",
              contactEmail: "zhangsan@example.com",
              arrivalTime: "14:00",
              specialRequests: "希望安排高层房间",
            }
          : null,
      shippingFee: route.query.type === "hotel" ? 0 : 10,
    };
  } catch (error) {
    console.error("获取订单详情失败:", error);
    ElMessage.error("获取订单详情失败");
    router.push("/user/orders");
  } finally {
    loading.value = false;
  }
};

// 获取物流信息
const fetchLogistics = async (orderId) => {
  if (orderInfo.value.type !== 'product') return;
  
  try {
    const response = await axios.get(`/orders/${orderId}/logistics`);
    if (response) {
      orderInfo.value.logistics = response;
    }
  } catch (error) {
    console.error("获取物流信息失败:", error);
    // 保留测试数据
  }
};

// 页面加载
onMounted(async () => {
  const orderId = route.params.id || route.query.orderId;
  if (!orderId) {
    ElMessage.error("订单ID不能为空");
    router.push("/user/orders");
    return;
  }
  await fetchOrderDetail(orderId);
  
  // 如果是商品订单且已发货，获取物流信息
  if (orderInfo.value.type === 'product' && 
      ['shipped', 'delivered', 'completed'].includes(orderInfo.value.status)) {
    await fetchLogistics(orderId);
  }
});
</script>

<style lang="scss" scoped>
.order-detail-page {
  :deep(.el-tag) {
    @apply rounded-md;

    &.el-tag--success {
      @apply bg-green-50 text-green-600 border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-700;
    }

    &.el-tag--warning {
      @apply bg-yellow-50 text-yellow-600 border-yellow-200 dark:bg-yellow-900/20 dark:text-yellow-400 dark:border-yellow-700;
    }

    &.el-tag--info {
      @apply bg-gray-50 text-gray-600 border-gray-200 dark:bg-gray-900/20 dark:text-gray-400 dark:border-gray-700;
    }
  }

  :deep(.el-timeline) {
    .el-timeline-item__node {
      @apply dark:bg-gray-600;

      &.el-timeline-item__node--primary {
        @apply dark:bg-primary-500;
      }
    }

    .el-timeline-item__wrapper {
      .el-timeline-item__timestamp {
        @apply dark:text-gray-400;
      }

      .el-timeline-item__content {
        @apply dark:text-gray-300;
      }
    }
  }

  :deep(.el-steps) {
    .el-step__title {
      @apply dark:text-gray-400;

      &.is-success {
        @apply dark:text-green-400;
      }

      &.is-process {
        @apply dark:text-primary-400;
      }
    }

    .el-step__description {
      @apply dark:text-gray-500;

      &.is-success {
        @apply dark:text-green-500;
      }

      &.is-process {
        @apply dark:text-primary-500;
      }
    }
  }
}
</style>
